package gsw.tool.pluggable.hook.hook;

import android.app.Instrumentation;
import android.util.Log;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import gsw.tool.pluggable.hook.handler.BaseHandlerClass;
import gsw.tool.pluggable.hook.handler.HandlerInstrumentation;
import gsw.tool.pluggable.compat.CompatActivityThread;
import gsw.tool.pluggable.utils.reflect.FieldUtils;

/**
 * Hook当前ActivityThread的mInstrumentation，用来修改Activity的生命周期方法。
 * 注意：开启新进程打开插件时，需要对新进程的ActivityThread的mInstrumentation进行Hook。
 */
public class HookInstrumentation extends BaseHook {

    private static final String TAG = HookInstrumentation.class.getSimpleName();
    private List<HandlerInstrumentation> mPluginInstrumentations = new ArrayList<HandlerInstrumentation>();

    @Override
    protected BaseHandlerClass createHookHandle() {
        return null;
    }

    @Override
    public void onInit(ClassLoader classLoader) {
        Object target = null;
        try {
            target = CompatActivityThread.currentActivityThread();
            Class ActivityThreadClass = CompatActivityThread.activityThreadClass();
            Field mInstrumentationField = FieldUtils.getField(ActivityThreadClass, "mInstrumentation");
            Instrumentation mInstrumentation = (Instrumentation) FieldUtils.readField(mInstrumentationField, target);
            if (!HandlerInstrumentation.class.isInstance(mInstrumentation)) {
                HandlerInstrumentation pit = new HandlerInstrumentation(mInstrumentation);
                pit.setEnable(isEnable());
                mPluginInstrumentations.add(pit);
                //替换ActivityThread.mInstrumentation，拦截组件调度消息
                FieldUtils.writeField(mInstrumentationField, target, pit);
            } else {
                Log.i(TAG, "Instrumentation has installed,skip");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
